package cn.wolfcode.web.advice;

import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.exception.BusinessException;
import cn.wolfcode.mapper.LogInfoMapper;
import cn.wolfcode.util.UserContext;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class ExceptionControllerAdvice {
    @Autowired
    private LogInfoMapper logInfoMapper;

    //处理异常类型
    @ExceptionHandler(BusinessException.class)
    public void handlerBusinessException(BusinessException e, HttpServletResponse response, HandlerMethod handlerMethod) throws IOException {
        //判断是那种请求
        //获取ResponseBody注解，判断是js请求还是页面请求
        ResponseBody methodAnnotation = handlerMethod.getMethodAnnotation(ResponseBody.class);
        if (methodAnnotation!=null){
            //设置响应格式
            response.setContentType("application/json;charset=utf-8");
            //把JsonResult转成js对象
            String jsonString = JSON.toJSONString(new JsonResult(e.getMessage(), false));
            response.getWriter().write(jsonString);
        }else {
            response.sendRedirect("/error");
        }

    }


    //处理异常类型
    @ExceptionHandler(Exception.class)
    public void handlerException(Exception e, HttpServletResponse response, HandlerMethod handlerMethod) throws IOException {
        e.printStackTrace();
        String uuid = UserContext.getUUID();
        logInfoMapper.updateErrorByUUID(e.toString(),uuid);
        //判断是那种请求
        //获取ResponseBody注解，判断是js请求还是页面请求
        ResponseBody methodAnnotation = handlerMethod.getMethodAnnotation(ResponseBody.class);
        if (methodAnnotation!=null){
            //设置响应格式
            response.setContentType("application/json;charset=utf-8");
            //把JsonResult转成js对象
            String jsonString = JSON.toJSONString(new JsonResult("系统错误，请求稍后尝试！", false));
            response.getWriter().write(jsonString);
        }else {
            response.sendRedirect("/error");
        }

    }
}
